package ua.kpi.apolonov.IO;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
import ua.kpi.apolonov.questions.Question;

/**
 * Class for management of input and output 
 * @version 1.1 25.02.2013
 * @author Yegor Apolonov
 */

public class InputOutput {
    
    private InputStream inputStream;
    private OutputStream outputStream;
    private PrintStream printStream;
    private Scanner answersScanner;
    private int questionCounter = 0;
    
    public InputOutput(InputStream inputStream, OutputStream outputStream) {
        this.inputStream = inputStream;
        this.outputStream = outputStream;
        this.printStream = new PrintStream(this.outputStream);
        this.answersScanner = new Scanner(this.inputStream);
    }

    public String inputAnswers() {
        return answersScanner.nextLine();
    }
    
    public void outQuestionBlock(Question question) {
    	questionCounter = upCounter(questionCounter);
    	String formatQuestion = String.format("\nВопрос№%d: %s",questionCounter, question.getQuestionText());
        printStream.print(formatQuestion);
        printStream.print(question.getInquiry());
    }
    
    public void outResultToDislpay(float result, float maxScore) {
        printStream.print(String.format("Ваш результат - %.2f из %.2f", result, maxScore));
    }
    
    public void helloUser() {
    	printStream.print("\nЗдравстуйте, пользователь системы тестирования!\n" +
    			          "Пожалуйста, введите желаемое имя своей учетной записи:\n>> ");
    }
    
    public String reenterUserName() {
    	printStream.print("\nИзвините, такая учетная запись уже есть, введите другое имя учетной записи:\n>> ");
    	return inputAnswers();
    }
    
    public void outResultToFile(String userName, float result, float maxScore) {
    	Calendar testDate = new GregorianCalendar();
    	String userFileName = String.format("%s%s%s", "src/ua/kpi/apolonov/users/", userName, ".txt");  
    	ExternalFileService fileWriter = new ExternalFileService(userFileName);
    	fileWriter.writeToExternalFile(String.format("%s result=%.2f of max score=%.2f\n", testDate.getTime().toString(), result, maxScore));
    }
    
    private int upCounter(int previousCounter) {
    	return previousCounter + 1;
    }
    
}